<template>
	<div class="external-api-test">
		<a-card title="外部API连接器测试">
			<a-space direction="vertical" style="width: 100%">
				<!-- 测试配置 -->
				<a-card size="small" title="测试配置">
					<a-form layout="vertical">
						<a-row :gutter="16">
							<a-col :span="12">
								<a-form-item label="API基础地址">
									<a-input v-model:value="testConfig.baseUrl" placeholder="https://jsonplaceholder.typicode.com" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item label="认证类型">
									<a-select v-model:value="testConfig.authType">
										<a-select-option value="NONE">无认证</a-select-option>
										<a-select-option value="BEARER_TOKEN">Bearer Token</a-select-option>
										<a-select-option value="API_KEY">API Key</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
						</a-row>

						<a-form-item v-if="testConfig.authType === 'BEARER_TOKEN'" label="访问令牌">
							<a-input-password v-model:value="testConfig.auth_token" placeholder="请输入访问令牌" />
						</a-form-item>

						<a-form-item v-if="testConfig.authType === 'API_KEY'" label="API密钥">
							<a-input-password v-model:value="testConfig.auth_apiKey" placeholder="请输入API密钥" />
						</a-form-item>
					</a-form>
				</a-card>

				<!-- 测试API列表 -->
				<a-card size="small" title="测试API列表">
					<a-table :columns="apiColumns" :data-source="testApis" :pagination="false" size="small">
						<template #bodyCell="{ column, record }">
							<template v-if="column.dataIndex === 'action'">
								<a-space>
									<a-button :loading="record.testing" size="small" type="primary" @click="testApi(record)">
										测试
									</a-button>
									<a-button :disabled="!record.result" size="small" @click="viewResult(record)"> 查看结果 </a-button>
								</a-space>
							</template>
							<template v-if="column.dataIndex === 'status'">
								<a-tag :color="getStatusColor(record.status)">
									{{ record.status }}
								</a-tag>
							</template>
						</template>
					</a-table>
				</a-card>

				<!-- 测试结果 -->
				<a-card v-if="selectedResult" size="small" title="测试结果">
					<a-descriptions :column="2" bordered size="small">
						<a-descriptions-item label="API路径">{{ selectedResult.path }}</a-descriptions-item>
						<a-descriptions-item label="请求方法">{{ selectedResult.method }}</a-descriptions-item>
						<a-descriptions-item label="响应状态">
							<a-tag :color="selectedResult.success ? 'green' : 'red'">
								{{ selectedResult.success ? '成功' : '失败' }}
							</a-tag>
						</a-descriptions-item>
						<a-descriptions-item label="响应时间">{{ selectedResult.responseTime }}ms</a-descriptions-item>
					</a-descriptions>

					<a-divider />

					<a-tabs>
						<a-tab-pane key="response" tab="响应数据">
							<pre class="json-viewer">{{ JSON.stringify(selectedResult.data, null, 2) }}</pre>
						</a-tab-pane>
						<a-tab-pane v-if="selectedResult.error" key="error" tab="错误信息">
							<a-alert :message="selectedResult.error" type="error" />
						</a-tab-pane>
					</a-tabs>
				</a-card>
			</a-space>
		</a-card>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import { message } from 'ant-design-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'

	// 测试配置
	const testConfig = reactive({
		baseUrl: 'https://jsonplaceholder.typicode.com',
		authType: 'NONE',
		timeout: '30000',
		retryCount: '3',
		auth_token: '',
		auth_apiKey: ''
	})

	// 测试API列表
	const testApis = ref([
		{
			path: '/posts',
			method: 'GET',
			description: '获取文章列表',
			status: '未测试',
			testing: false,
			result: null
		},
		{
			path: '/posts/1',
			method: 'GET',
			description: '获取单个文章',
			status: '未测试',
			testing: false,
			result: null
		},
		{
			path: '/users',
			method: 'GET',
			description: '获取用户列表',
			status: '未测试',
			testing: false,
			result: null
		},
		{
			path: '/users/1',
			method: 'GET',
			description: '获取单个用户',
			status: '未测试',
			testing: false,
			result: null
		}
	])

	// 选中的测试结果
	const selectedResult = ref(null)

	// 表格列定义
	const apiColumns = [
		{
			title: 'API路径',
			dataIndex: 'path',
			width: 150
		},
		{
			title: '请求方法',
			dataIndex: 'method',
			width: 100
		},
		{
			title: '描述',
			dataIndex: 'description'
		},
		{
			title: '状态',
			dataIndex: 'status',
			width: 100
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: 150
		}
	]

	// 测试单个API
	const testApi = async (api) => {
		try {
			api.testing = true
			api.status = '测试中'

			const startTime = Date.now()

			// 构建测试连接器配置
			const connectorConfig = {
				type: 'EXTERNAL_API',
				config: {
					...testConfig,
					apis: JSON.stringify([
						{
							path: api.path,
							method: api.method,
							description: api.description
						}
					])
				}
			}

			// 先测试连接
			await dataConnectorApi.testConnection(connectorConfig)

			// 模拟API调用（这里可以扩展为实际的API调用）
			const response = await fetch(testConfig.baseUrl + api.path)
			const data = await response.json()

			const endTime = Date.now()
			const responseTime = endTime - startTime

			// 保存测试结果
			api.result = {
				path: api.path,
				method: api.method,
				success: response.ok,
				responseTime,
				data,
				error: response.ok ? null : `HTTP ${response.status}: ${response.statusText}`
			}

			api.status = response.ok ? '成功' : '失败'

			if (response.ok) {
				message.success(`API ${api.path} 测试成功`)
			} else {
				message.error(`API ${api.path} 测试失败`)
			}
		} catch (error) {
			console.error('API测试失败:', error)
			api.status = '失败'
			api.result = {
				path: api.path,
				method: api.method,
				success: false,
				responseTime: 0,
				data: null,
				error: error.message || '未知错误'
			}
			message.error(`API ${api.path} 测试失败: ${error.message}`)
		} finally {
			api.testing = false
		}
	}

	// 查看测试结果
	const viewResult = (api) => {
		selectedResult.value = api.result
	}

	// 获取状态颜色
	const getStatusColor = (status) => {
		switch (status) {
			case '成功':
				return 'green'
			case '失败':
				return 'red'
			case '测试中':
				return 'blue'
			default:
				return 'default'
		}
	}
</script>

<style scoped>
	.external-api-test {
		padding: 16px;
	}

	.json-viewer {
		background-color: #f5f5f5;
		padding: 12px;
		border-radius: 4px;
		font-family: 'Courier New', monospace;
		font-size: 12px;
		max-height: 400px;
		overflow-y: auto;
	}

	:deep(.ant-card-head-title) {
		font-weight: 600;
	}

	:deep(.ant-descriptions-item-label) {
		font-weight: 500;
	}
</style>
